<template>
  <div>
    <comments-container v-show="commenting" @commented="handleCommented" />
    <div class="easy-container" v-loading="loading">
      <div ref="commentsTop"></div>
      <div v-if="!comments.length" class="easy-container-x2 text-center info">当前没有跟帖</div>
      <comments-list-item v-for="item in comments" :key="item.id" :comment="item" />
    </div>
    <pagination
      :current-page="pagination.current"
      :page-count="pagination.count"
      clear-query
      class="m-t-0"
    />
  </div>
</template>

<script>
import { formatComments } from './format';
import CommentsListItem from './follow-comments/comments-list-item';
import CommentsContainer from './follow-comments/comments-container';

export default {
  name: 'documents-follow-comments', // 资源下的跟帖区（原评论区）
  props: {
    commenting: Boolean,
  },
  components: {
    CommentsListItem,
    CommentsContainer,
  },
  data() {
    return {
      loading: false,
      comments: [],
      pagination: {
        current: null,
        count: null,
      },
    };
  },
  computed: {
    // 加载评论列表所需参数
    loadCommentsParams() {
      return {
        placement: 'ProductFile',
        placementId: this.$route.params.docId,
        page: this.$route.query.page,
      };
    },
  },
  created() { this.loadComments(); },
  methods: {
    // 加载评论列表
    loadComments() {
      this.loading = true;
      this.$api.comments.index(this.loadCommentsParams)
        .then((res) => {
          this.comments = formatComments(res.data);
          this.pagination.current = res.kaminari.current_page;
          this.pagination.count = res.kaminari.total_pages;
          if (this.loadCommentsParams.page) { // 当有page参数（即翻页时），定位到评论区顶部
            this.scrollTopCommentsTop();
          }
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
    // 有新回答
    handleCommented(comment) {
      this.comments.push(comment);
      this.$emit('update:commenting', false);
    },
    // 加载新页码时翻到顶
    scrollTopCommentsTop() {
      this.$refs.commentsTop.scrollIntoView({ block: 'center' });
    },
  },
  watch: {
    loadCommentsParams(newVal, oldVal) {
      if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) { // 未知的原因，楼中楼改变参数时，会触发这里
        this.loadComments();
      }
    },
  },
};
</script>

<style></style>
